<script lang="ts" setup>
import {
  getOneByCondition,
  getReadonly,
  insertOne,
  reSetDialogModel,
  updateOne,
  urls,
  getProductionReferenceListFromPurchaseProduction
} from '@/index';

import type { DialogModel, PurchaseProduction } from '@/index.d';
import type { FormInstance, FormRules } from 'element-plus';
import TimeLine from './TimeLine.vue';
import { useRequest } from 'vue-request';

const dialogModel = defineModel<DialogModel<PurchaseProduction>>('dialogModel', {
  required: true
});

const { updateForbidden } = getReadonly(dialogModel.value);

const formData = reactive<PurchaseProduction>({
  id: 0,
  partType: '锻件',
  partStatus: '进行'
});

const setFormData = async (res: PurchaseProduction) => {
  formData.id = res.id;
  formData.creator = res.creator;
  formData.createTime = res.createTime;
  formData.updater = res.updater;
  formData.updateTime = res.updateTime;
  formData.productionReference = res.productionReference;
  formData.supplierName = res.supplierName;
  formData.partName = res.partName;
  formData.partReference = res.partReference;
  formData.partType = res.partType;
  formData.partAttachmentUuid = res.partAttachmentUuid;
  formData.partAttachmentLink = res.partAttachmentLink;
  formData.partStatus = res.partStatus;
  formData.note = res.note;
  formData.signDate = res.signDate;
  formData.requiredDate = res.requiredDate;
  formData.finishedDate = res.finishedDate;
};

const reSetFormData = () => {
  reSetDialogModel(dialogModel);
  formData.id = 0;
  delete formData.productionReference;
  delete formData.supplierName;
  delete formData.partName;
  delete formData.partReference;
  delete formData.partType;
  delete formData.partAttachmentUuid;
  delete formData.partAttachmentLink;
  delete formData.partStatus;
  delete formData.note;
  delete formData.signDate;
  delete formData.requiredDate;
  delete formData.finishedDate;
};

watch(
  () => dialogModel.value.visible,
  value => {
    value && (formData.id = dialogModel.value.id as number);
    !value && reSetFormData();
  },
  {
    immediate: true
  }
);

watch(
  () => formData.id,
  async (value: number | undefined) => {
    if (value) {
      const res = await getOneByCondition<PurchaseProduction>(urls.purchaseProduction, 'id', value);
      res && setFormData(res);
    }
  },
  {
    immediate: true
  }
);

const formDataRef = ref<FormInstance>();

interface FormDataRules {
  productionReference: string;
  supplierName: string;
  partName: string;
  partReference: string;
}

const formDataRules = computed(() => {
  switch (dialogModel.value.type) {
    case 'view':
      return reactive({});

    case 'update':
      return reactive<FormRules<FormDataRules>>({
        productionReference: [{ required: true, message: '生产令号不能为空', trigger: 'blur' }],
        supplierName: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
        partName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
        partReference: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }]
      });

    case 'insert':
      return reactive<FormRules<FormDataRules>>({
        productionReference: [{ required: true, message: '生产令号不能为空', trigger: 'blur' }],
        supplierName: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
        partName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
        partReference: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }]
      });
  }
});

const saveFormData = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl
    .validate()
    .then(async valid => {
      if (valid) {
        if (dialogModel.value.id === 0) {
          const res = (await insertOne<PurchaseProduction>(
            urls.purchaseProduction,
            formData
          )) as PurchaseProduction;
          if (res) {
            setFormData(res);
            dialogModel.value.id = res.id as number;
            dialogModel.value.type = 'update';
            dialogModel.value.change = true;
          }
        } else {
          const tempFormData: PurchaseProduction = {
            id: formData.id,
            productionReference: formData.productionReference,
            supplierName: formData.supplierName,
            partName: formData.partName,
            partReference: formData.partReference,
            partType: formData.partType,
            partStatus: formData.partStatus,
            note: formData.note,
            signDate: formData.signDate,
            requiredDate: formData.requiredDate,
            finishedDate: formData.finishedDate
          };

          const res = (await updateOne<PurchaseProduction>(
            urls.purchaseProduction,
            tempFormData
          )) as PurchaseProduction;

          if (res) {
            dialogModel.value.change = true;
            formData.updater = res.updater;
            formData.updateTime = res.updateTime;
          }
        }
      }
    })
    .catch(res => console.log(res));
};

interface ProductionReferenceItem {
  value: string;
}

const { data: productionReferenceListData } = useRequest(() =>
  getProductionReferenceListFromPurchaseProduction()
);

const productionReferenceList = computed(() => {
  const productionReferenceList = ref<ProductionReferenceItem[]>([]);
  productionReferenceListData.value?.map(item => {
    productionReferenceList.value.push({
      value: item
    });
  });
  return productionReferenceList.value;
});

const createProductionReferenceFilter = (queryString: string) => {
  return (productionReference: ProductionReferenceItem) => {
    return productionReference.value.toLowerCase().includes(queryString.toLowerCase());
  };
};

const queryProductionReferenceSearch = (queryString: string, cb: any) => {
  const results = queryString
    ? productionReferenceList.value?.filter(createProductionReferenceFilter(queryString))
    : productionReferenceList.value;
  cb(results);
};
</script>
<template>
  <HqDialogDetail
    :dialog-model="dialogModel"
    @submit="saveFormData(formDataRef)"
    operate-record
    :operation="formData"
  >
    <template #default>
      <el-card shadow="hover">
        <template #header>基本信息</template>
        <template #default>
          <hq-form :model="formData" ref="formDataRef" :rules="formDataRules">
            <el-row :gutter="5">
              <hq-col v-show="false">
                <el-form-item label="id" prop="id">
                  <el-input v-model="formData.id" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="生产令号" prop="productionReference">
                  <el-autocomplete
                    v-model.trim="formData.productionReference"
                    :fetch-suggestions="queryProductionReferenceSearch"
                    :disabled="updateForbidden"
                    clearable
                  />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="供应商" prop="supplierName">
                  <el-select
                    v-model="formData.supplierName"
                    placeholder="请选择供应商"
                    filterable
                    clearable
                    :readonly="updateForbidden"
                  >
                    <HqRelationOptions />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="产品名称" prop="partName">
                  <el-input v-model.trim="formData.partName" :readonly="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="产品编号" prop="partReference">
                  <el-input v-model.trim="formData.partReference" :readonly="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="产品类型" prop="partType">
                  <el-select v-model="formData.partType" :disabled="updateForbidden">
                    <el-option label="锻件" value="锻件" />
                    <el-option label="板材" value="板材" />
                    <el-option label="其它" value="其它" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="当前状态" prop="partStatus">
                  <el-select v-model="formData.partStatus" :disabled="updateForbidden">
                    <el-option label="进行" value="进行" />
                    <el-option label="完成" value="完成" />
                    <el-option label="取消" value="取消" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="合同签订日期" prop="signDate">
                  <el-date-picker
                    v-model="formData.signDate"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :readonly="updateForbidden"
                  />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="要求完成日期" prop="requiredDate">
                  <el-date-picker
                    v-model="formData.requiredDate"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :readonly="updateForbidden"
                  />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="实际完成日期" prop="finishedDate">
                  <el-date-picker
                    v-model="formData.finishedDate"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :readonly="updateForbidden"
                  />
                </el-form-item>
              </hq-col>
            </el-row>
          </hq-form>
        </template>
      </el-card>
      <el-card shadow="hover" v-if="formData.partAttachmentUuid">
        <template #header>附件</template>
        <template #default>
          <HqUploadOne
            :key-word="formData.partAttachmentUuid!"
            :disabled="dialogModel.type !== 'update'"
          />
        </template>
      </el-card>
    </template>
  </HqDialogDetail>
</template>
<style lang="scss" scoped></style>
